package andanyoung.springcloud.common.config;

import okhttp3.OkHttpClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Configuration
@EnableHystrix
@EnableHystrixDashboard
public class RibbonConfig {

  @Bean
  @LoadBalanced
  public RestTemplate restTemplate() {
    return new RestTemplate();
  }

  /**
   * 自定义OK HTTP Client的参数
   *
   * @return
   */
  @Bean
  public OkHttpClient.Builder okHttpClientBuilder() {
    return new OkHttpClient.Builder()
        // 读取超时时间（不包含解析地址，提交请求的耗时）
        .readTimeout(2, TimeUnit.SECONDS)
        // 写入超时时间
        .writeTimeout(5, TimeUnit.SECONDS)
        // 连接远程服务器超时时间
        .connectTimeout(3, TimeUnit.SECONDS)
        // 如果连接远程服务器失败是否重试
        .retryOnConnectionFailure(true)
        // 当HTTP返回码为3xx（重定向）时，是否执行重定向操作
        .followRedirects(true);
  }
}
